package com.letv.whatslive.mongo.dao;


import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.ForbiddenDevice;
import com.letv.whatslive.model.convert.ForbiddenDeviceConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 用户collection操作DAO
 * Created by shenyue1 on 2016/1/13.
 */
@Repository
public class ForbiddenDeviceDAO extends BaseDAO {

    private final static Logger logger = LoggerFactory.getLogger(ForbiddenDeviceDAO.class);

    protected String collectionName = "forbiddenDevice";

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    /**
     * 根据条件查询设备黑名单列表
     *
     * @param params 模糊查询的查询条件
     * @param orders 排序的条件
     * @param start  查询条件的开始分页数
     * @param limit  查询条件的分页每页条数
     * @return
     */
    public List<ForbiddenDevice> getForbiddenDeviceListByParams(Map<String, Object> params, Map<String, Object> orders, Integer start, Integer limit) {

        List<ForbiddenDevice> result = Lists.newArrayList();

        // 查询件数
        if (limit == null) {
            limit = DEFAULT_NUM;
        }

        try {

            // dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject order = getOrderParams(orders);
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).sort(order).limit(limit);
            while (cur.hasNext()) {

                DBObject dbObject = cur.next();
                ForbiddenDevice forbiddenDevice = ForbiddenDeviceConvert.castDBObjectToForbiddenDevice(dbObject);
                result.add(forbiddenDevice);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }

        return result;
    }

    /**
     * 根据指定ID获取被屏蔽设备信息
     * @param id
     * @return forbiddenDevice
     */
    public ForbiddenDevice getForbiddenDevicebyId(Long id) {

        BasicDBObject query = new BasicDBObject();
        ForbiddenDevice forbiddenDevice = new ForbiddenDevice();
        query.put("_id", id);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) {

            return null;
        }
        try {

            forbiddenDevice = ForbiddenDeviceConvert.castDBObjectToForbiddenDevice(dbObject);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return forbiddenDevice;
    }

    /**
     * 判断指定Device是否存在
     * @param deviceId 设备ID
     * @return isExists
     */
    public boolean isExists(String deviceId) {

        boolean isExists = false;
        BasicDBObject query = new BasicDBObject();
        query.put("deviceId", deviceId);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject != null) {

            isExists = true;
        }

        return isExists;
    }

    /**
     * 根据查询条件查询被屏蔽设备的数量
     * @param params 查询条件参数
     * @return 满足条件的文档记录数
     */
    public Long countForbiddenDeviceByParams(Map params) {

        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    /**
     * 追加被屏蔽设备信息
     *
     * @param forbiddenDevice
     * @return
     */
    public int addForbiddenDevice(ForbiddenDevice forbiddenDevice) {

        // 追加件数
        int insertCount = 1;

        try {

            forbiddenDevice.setId(getAutoIncrementId());
            DBObject dbo =ForbiddenDeviceConvert.castForbiddenDeviceToDBObject(forbiddenDevice);
//            DBRef deviceRef = new DBRef("device", forbiddenDevice.getDeviceId());
//            dbo.put("device", deviceRef);
            this.dbCollection.insert(dbo);

        } catch (Exception e) {

            insertCount = 0;
            logger.error(e.getMessage(), e);
        }

        return insertCount;
    }

    /**
     * 更新被屏蔽设备信息
     *
     * @param forbiddenDevice
     * @return updateCount 更新件数
     */
    public int updateForbiddenDevice(ForbiddenDevice forbiddenDevice) {

        // 更新件数
        int updateCount = 0;

        try {

            DBObject queryCondition = new BasicDBObject();
            long id = forbiddenDevice.getId();
            queryCondition.put("_id", id);
            DBObject setValue = new BasicDBObject();;
            // 更新屏蔽原因
//            setValue.put("forbiddenReason", forbiddenDevice.getForbiddenReason());

            DBObject values = new BasicDBObject("$set", setValue);

            WriteResult writeResult = this.dbCollection.update(queryCondition, values, false, false);
            updateCount = writeResult.getN();
        } catch (Exception e) {

            logger.error(e.getMessage(), e);
        }

        return updateCount;
    }

    /**
     * 根据id删除指定设备
     * @param id
     */
    public int deleteForbiddenDevice(Long id) {

        // 更新件数
        int deleteCount = 0;

        try {
            BasicDBObject query = new BasicDBObject();
            query.put("_id", id);
            WriteResult writeResult = this.dbCollection.remove(query);

            deleteCount = writeResult.getN();
        } catch (Exception e) {

            logger.error(e.getMessage(), e);
        }

        return deleteCount;
    }

    /**
     * 根据设备ID删除指定设备
     * @param deviceId 设备ID
     */
    public int deleteForbiddenDeviceByDeviceId(String deviceId) {

        // 更新件数
        int deleteCount = 0;

        try {
            BasicDBObject query = new BasicDBObject();
            query.put("deviceId", deviceId);
            WriteResult writeResult = this.dbCollection.remove(query);

            deleteCount = writeResult.getN();
        } catch (Exception e) {

            logger.error(e.getMessage(), e);
        }

        return deleteCount;
    }

    /**
     * 获取排序的BasicDBObject对象
     * @param orders
     * @return
     */
    private BasicDBObject getOrderParams(Map<String, Object> orders) {

        BasicDBObject order = new BasicDBObject();
        if (orders != null && orders.size() > 0) {

            for (String key : orders.keySet()) {

                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        } else {

            // 默认按照屏蔽时间降序
            order.append("createTime", -1);
        }
        return order;
    }

    /**
     * 根据查询参数Map获取查询条件对象
     * @param params 查询参数Map
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params) {

        BasicDBObject query = new BasicDBObject();

        if (params != null && params.size() > 0) {
            if (params.get("deviceId") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("deviceId") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("deviceId", pattern);
            }

            if(params.get("dateFrom") != null && params.get("dateTo") != null) {

                query.put("createTime", new BasicDBObject("$gte",
                        ObjectUtils.toLong(params.get("dateFrom"))).append("$lte", ObjectUtils.toLong(params.get("dateTo"))));
            } else if (params.get("dateFrom") == null && params.get("dateTo") != null) {

                query.put("createTime", new BasicDBObject("$lte", ObjectUtils.toLong(params.get("dateTo"))));
            } else if (params.get("dateFrom") != null && params.get("dateTo") == null) {

                query.put("createTime", new BasicDBObject("$gte", ObjectUtils.toLong(params.get("dateFrom"))));
            }
        }
        return query;
    }
}
